//
//  MemberTrackDetailViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/6/11.
//

#import "MemberTrackDetailViewController.h"
#import "MemberTrackDetailAnnotationView.h"
#import "TrackEventAnnotationView.h"
#import "TrackDotAnnotationView.h"
#import "RouteAnnotationView.h"
#import "TrackDotTableViewCell.h"
#import "MapHierarchyView.h"
#import "XDXMapView.h"
#import "UIImageView+WebCache.h"

@interface MemberTrackDetailViewController ()<UIGestureRecognizerDelegate,MKMapViewDelegate,UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, assign) CGFloat originY;
@property (nonatomic, strong) XDXMapView *mapView;
@property (nonatomic, strong) UILabel *start;
@property (nonatomic, strong) UILabel *end;
@property (nonatomic, strong) NSMutableArray *annotationArray;
@property (nonatomic, strong) NSMutableArray *overlayArray;
@property (nonatomic, strong) UIView *dotView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MKPointAnnotation *annotation;

@end

@implementation MemberTrackDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initUI];
}

- (void)initUI
{
    self.mapView = [[XDXMapView alloc] initWithFrame:CGRectMake(0, STATUSHEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-STATUSHEIGHT)];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.rotateEnabled = NO;
    self.mapView.showsBuildings = YES;
    self.mapView.zoomLevel = 15;
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    NSInteger mapType = [[[NSUserDefaults standardUserDefaults] objectForKey:MapType] integerValue];
    NSInteger showTraffic = [[[NSUserDefaults standardUserDefaults] objectForKey:ShowTraffic] boolValue];
    NSInteger roadNet = [[[NSUserDefaults standardUserDefaults] objectForKey:RoadNet] boolValue];
    if (mapType==0) {
        self.mapView.mapType = MKMapTypeStandard;
    }else if (mapType==1){
        self.mapView.mapType = (showTraffic==0)?(roadNet==0?MKMapTypeSatellite:MKMapTypeHybrid):MKMapTypeHybridFlyover;
    }else if (mapType==2){
        if (self.mapView.zoomLevel>16.0) {
            self.mapView.mapType = (showTraffic==0)?(roadNet==0?MKMapTypeSatellite:MKMapTypeHybrid):MKMapTypeHybridFlyover;
        }else{
            self.mapView.mapType = MKMapTypeStandard;
        }
    }
    self.mapView.showsTraffic = showTraffic;
    
    UIView *top = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, STATUSHEIGHT)];
    top.backgroundColor = RealWhiteColor;
    [self.view addSubview:top];
    
    UILabel *slider = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-42)/2, 8, 42, 4)];
    slider.layer.masksToBounds = YES;
    slider.backgroundColor =  GraryMiddleColor;
    [slider.layer setCornerRadius:2];
    [top addSubview:slider];
    
    UILabel *nickName = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(slider.frame), SCREEN_WIDTH, STATUSHEIGHT-CGRectGetMaxY(slider.frame))];
    nickName.textColor = RealBlackColor;
    nickName.font = MEDIUM_FONT(16);
    nickName.textAlignment = NSTextAlignmentCenter;
    nickName.text = [NSString stringWithFormat:@"%@",_info[@"nickName"]];
    [top addSubview:nickName];
    
    UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-48, CGRectGetMaxY(slider.frame)+(nickName.height-30)/2, 30, 30)];
    [close setImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
    [top addSubview:close];
    [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIView *left = [[UIView alloc] initWithFrame:CGRectMake(0, STATUSHEIGHT, 50, SCREEN_HEIGHT-STATUSHEIGHT)];
    [self.view addSubview:left];
    
    UIView *right = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-50, STATUSHEIGHT, 50, SCREEN_HEIGHT-STATUSHEIGHT)];
    [self.view addSubview:right ];

    UIButton *dotButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-50, SCREEN_HEIGHT, 40, 40)];
    [self.view addSubview:dotButton];
    CALayer *subDotLayer = [CALayer layer];
    subDotLayer.frame = dotButton.bounds;
    subDotLayer.cornerRadius = 20;
    subDotLayer.masksToBounds = NO;
    subDotLayer.backgroundColor = RealWhiteColor.CGColor;
    subDotLayer.shadowColor = RealBlackColor.CGColor;
    subDotLayer.shadowOffset = CGSizeMake(0,2);
    subDotLayer.shadowOpacity = 0.3;
    subDotLayer.shadowRadius = 3;
    [dotButton.layer addSublayer:subDotLayer];
    UIImageView *dotImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 20, 20)];
    [dotImg setImage:[UIImage imageNamed:@"dot"]];
    [dotButton addSubview:dotImg];
    [[dotButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self drawTrackDotOverlayAndAnnotion];
    }];
    [self drawOverlayAndAnnotion];
    
    if ([_info[@"title"] containsString:@"行程"] || [_info[@"title"] containsString:@"驾车"]) {
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-STATUSHEIGHT-300, SCREEN_WIDTH, 300)];
        if ([_info[@"title"] containsString:@"行程"]) {
            [bottomView setFrame:CGRectMake(0, SCREEN_HEIGHT-STATUSHEIGHT-230, SCREEN_WIDTH, 230)];
        }
        [self.view addSubview:bottomView];
        
        UIVisualEffectView *visualEffect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
        visualEffect.frame = CGRectMake(0, 0, bottomView.width, bottomView.height);
        [bottomView addSubview:visualEffect];
        
        dotButton.y = bottomView.y-80;
        
        UIButton *mapImg = [[UIButton alloc] initWithFrame:CGRectMake(16, 28, 42, 42)];
        mapImg.layer.masksToBounds = YES;
        [mapImg.layer setCornerRadius:8];
        mapImg.backgroundColor = WhiteColor;
        [bottomView addSubview:mapImg];
        if ([_info[@"title"] containsString:@"行程"]) {
            [mapImg setImage:[UIImage imageNamed:@"walk"] forState:UIControlStateNormal];
        }else{
            [mapImg setImage:[UIImage imageNamed:@"drive"] forState:UIControlStateNormal];
        }
        
        UILabel *nickName = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(mapImg.frame)+8, 26, bottomView.width-CGRectGetMaxX(mapImg.frame)-131, 24)];
        nickName.font = REAL_MEDIUM_FONT(16);
        nickName.textColor = RealBlackColor;
        nickName.text = [NSString stringWithFormat:@"%@",_info[@"title"]];
        [bottomView addSubview:nickName];
        
        UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(nickName.x, CGRectGetMaxY(nickName.frame)+2, nickName.width, 20)];
        time.font = DEFAULT_FONT(13);
        time.textColor = GraryLightColor;
        time.text = [NSString stringWithFormat:@"用时 %@",[_info[@"timeRun"] substringWithRange:NSMakeRange(14, [_info[@"timeRun"] length]-15)]];
        [bottomView addSubview:time];
        
        UILabel *date = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-123, 26, 107, 46)];
        date.font = DEFAULT_FONT(13);
        date.textColor = GraryLightColor;
        date.textAlignment = NSTextAlignmentRight;
        date.text = [NSString stringWithFormat:@"%ld月%ld日",(long)[[_info[@"array"] lastObject][@"create_time"] substringWithRange:NSMakeRange(5, 2)].integerValue,(long)[[_info[@"array"] lastObject][@"create_time"] substringWithRange:NSMakeRange(8, 2)].integerValue];
        [bottomView addSubview:date];
        
        UIView *startView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(mapImg.frame)+18, SCREEN_WIDTH-32, 92)];
        startView.backgroundColor = RealWhiteColor;
        startView.layer.masksToBounds = YES;
        [startView.layer setCornerRadius:12];
        [bottomView addSubview:startView];
         
        UIImageView *startImg = [[UIImageView alloc] initWithFrame:CGRectMake(16, 15, 16, 16)];
        [startImg setImage:[UIImage imageNamed:@"start_de"]];
        [startView addSubview:startImg];
        
        UIImageView *dot = [[UIImageView alloc] initWithFrame:CGRectMake(23, CGRectGetMaxY(startImg.frame)+4, 1, 22)];
        dot.image = [UIImage imageNamed:@"map_de_dot"];
        [startView addSubview:dot];
        
        UIImageView *endImg = [[UIImageView alloc] initWithFrame:CGRectMake(14, CGRectGetMaxY(startImg.frame)+27, 20, 20)];
        [endImg setImage:[UIImage imageNamed:@"dingwei-3"]];
        [startView addSubview:endImg];
                                   
        _start = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(startImg.frame)+14, startImg.y, startView.width-CGRectGetMaxX(startImg.frame)-86, startImg.height)];
        _start.font = REAL_MEDIUM_FONT(15);
        _start.textColor = RealBlackColor;
        [startView addSubview:_start];
        {
            CLLocation *location = [[CLLocation alloc] initWithLatitude:[[_info[@"array"] firstObject][@"latitude"] floatValue] longitude:[[_info[@"array"] firstObject][@"longtitude"] floatValue]]; // 示例坐标
            CLGeocoder *geocoder = [[CLGeocoder alloc] init];
            [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
                if (error) {
                    NSMutableDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:[self.info[@"array"] firstObject][@"latitude"] forKey:@"lat"];
                    [param setValue:[self.info[@"array"] firstObject][@"longtitude"] forKey:@"lon"];
                    [param setValue:@"1" forKey:@"status"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPOST:@"/apps/data/reversecode"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                            self.start.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"street"]];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                } else {
                    if (placemarks.count > 0) {
                        CLPlacemark *placemark = [placemarks objectAtIndex:0];
                        self.start.text = [NSString stringWithFormat:@"%@",placemark.name];
                    } else {
                        NSLog(@"No placemarks found.");
                    }
                }
            }];
        }
        
        UILabel *startTime = [[UILabel alloc] initWithFrame:CGRectMake(startView.width-64, startImg.y, 50, startImg.height)];
        startTime.font = DEFAULT_FONT(12);
        startTime.textAlignment = NSTextAlignmentRight;
        startTime.textColor = GraryLightColor;
        startTime.text = [NSString stringWithFormat:@"%@",[[_info[@"array"] firstObject][@"create_time"] substringWithRange:NSMakeRange(11, 5)]];
        [startView addSubview:startTime];
       
        _end = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(startImg.frame)+12, endImg.y, startView.width-CGRectGetMaxX(endImg.frame)-84, endImg.height)];
        _end.font = REAL_MEDIUM_FONT(15);
        _end.textColor  =RealBlackColor;
        [startView addSubview:_end];
        {
            CLLocation *location = [[CLLocation alloc] initWithLatitude:[[_info[@"array"] lastObject][@"latitude"] floatValue] longitude:[[_info[@"array"] lastObject][@"longtitude"] floatValue]]; // 示例坐标
            CLGeocoder *geocoder = [[CLGeocoder alloc] init];
            [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
                if (error) {
                    NSMutableDictionary *param = [NSMutableDictionary dictionary];
                    [param setValue:[self.info[@"array"] lastObject][@"latitude"] forKey:@"lat"];
                    [param setValue:[self.info[@"array"] lastObject][@"longtitude"] forKey:@"lon"];
                    [param setValue:@"1" forKey:@"status"];
                    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                    [manager encryptedPOST:@"/apps/data/reversecode"
                    parameters:param
                    success:^(NSDictionary *responseObject) {
                        if ([responseObject[@"code"] integerValue]==200) {
                            self.end.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"street"]];
                        }
                    }
                    failure:^(NSError *aError) {
                        
                    }];
                } else {
                    if (placemarks.count > 0) {
                        CLPlacemark *placemark = [placemarks objectAtIndex:0];
                        self.end.text = [NSString stringWithFormat:@"%@",placemark.name];
                    } else {
                        NSLog(@"No placemarks found.");
                    }
                }
            }];
        }
        
        UILabel *endTime = [[UILabel alloc] initWithFrame:CGRectMake(startView.width-64, endImg.y, 50, endImg.height)];
        endTime.font = DEFAULT_FONT(12);
        endTime.textAlignment = NSTextAlignmentRight;
        endTime.textColor = GraryLightColor;
        endTime.text = [NSString stringWithFormat:@"%@",[[_info[@"array"] lastObject][@"create_time"] substringWithRange:NSMakeRange(11, 5)]];
        [startView addSubview:endTime];
        
        NSInteger unLockNum = 0;
        NSInteger embark = 0;
        for (int i = 0; i < [_info[@"array"] count]; i ++) {
            NSDictionary *dic = _info[@"array"][i];
            if ([dic[@"unlock"] integerValue]>0) {
                unLockNum = unLockNum+1;
                
                CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([dic[@"latitude"] doubleValue],[dic[@"longtitude"] doubleValue]);
                MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
                annotation.coordinate = coord;
                annotation.title    = @"unlock";
                annotation.subtitle = @"unlock";
                [self.mapView addAnnotation:annotation];
                [self.annotationArray addObject:annotation];
            }
            if ([dic[@"bark"] integerValue]>0){
                CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([dic[@"latitude"] doubleValue],[dic[@"longtitude"] doubleValue]);
                MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
                annotation.coordinate = coord;
                annotation.title    = @"bark";
                annotation.subtitle = @"bark";
                [self.mapView addAnnotation:annotation];
                [self.annotationArray addObject:annotation];
                embark = embark+1;
            }else{
                if (i>0 && !dic[@"bark"]) {
                    NSDictionary *firstDic = _info[@"array"][i-1];
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    dateFormatter.locale = [NSLocale systemLocale];
                    dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
                    NSDate *firstDate = [dateFormatter dateFromString:[firstDic[@"create_time"] substringToIndex:19]];
                    NSInteger firstSecond = [firstDate timeIntervalSince1970];
                    
                    NSDate *secondDate = [dateFormatter dateFromString:[dic[@"create_time"] substringToIndex:19]];
                    NSInteger secondSecond = [secondDate timeIntervalSince1970];
                    
                    CGFloat a = ([dic[@"speed"] floatValue]-[firstDic[@"speed"] floatValue])/(secondSecond-firstSecond);
                    if (a<-5) {
                        embark = embark+1;
                        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([dic[@"latitude"] doubleValue],[dic[@"longtitude"] doubleValue]);
                        MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
                        annotation.coordinate = coord;
                        annotation.title    = @"bark";
                        annotation.subtitle = @"bark";
                        [self.mapView addAnnotation:annotation];
                        [self.annotationArray addObject:annotation];
                    }
                }
            }
        }
        if ([_info[@"title"] containsString:@"驾车"]) {
            
            UIView *driveView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(startView.frame)+8, SCREEN_WIDTH-32, 63)];
            driveView.backgroundColor = RealWhiteColor;
            driveView.layer.masksToBounds = YES;
            [driveView.layer setCornerRadius:12];
            [bottomView addSubview:driveView];
            
            NSArray *array = @[@{@"title":@"最高速",@"textColor":RealBlackColor,@"num":[NSString stringWithFormat:@"%ld",(long)[_info[@"maxSpeed"] integerValue]],@"content":@"千米/时"},
                               @{@"title":@"用手机",@"textColor":YellowColor,@"num":[NSString stringWithFormat:@"%ld",(long)unLockNum],@"content":@"次"},
                               @{@"title":@"急刹车",@"textColor":RedColor,@"num":[NSString stringWithFormat:@"%ld",(long)embark],@"content":@"次"}];
            for (int i = 0; i < array.count; i ++) {
                UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(14+i*((driveView.width-28-62*3)/2+62), 12, 62, 16)];
                if (i==0) {
                    title.width = 120;
                }
                title.font = MEDIUM_FONT(13);
                title.text = array[i][@"title"];
                title.textColor = GraryTooLightColor;
                [driveView addSubview:title];
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(title.x, CGRectGetMaxY(title.frame)+7, title.width, 16)];
                label.layer.masksToBounds = NO;
                label.font = DEFAULT_FONT(13);
                label.textColor = RealBlackColor;
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",array[i][@"num"],array[i][@"content"]]];
                [str addAttribute:NSFontAttributeName value:RUBIK_BOLD_FONT(20) range:NSMakeRange(0, [array[i][@"num"] length])];
                [str addAttribute:NSForegroundColorAttributeName value:array[i][@"textColor"] range:NSMakeRange(0, [array[i][@"num"] length])];
                label.attributedText = str;
                [driveView addSubview:label];
            }
        }
    }else{
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-STATUSHEIGHT-132, SCREEN_WIDTH, 132)];
        [self.view addSubview:bottomView];
        
        dotButton.y = bottomView.y-80;
        
        UIVisualEffectView *visualEffect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
        visualEffect.frame = CGRectMake(0, 0, bottomView.width, bottomView.height);
        [bottomView addSubview:visualEffect];
        
        UIButton *mapImg = [[UIButton alloc] initWithFrame:CGRectMake(16, 28, 42, 42)];
        mapImg.layer.masksToBounds = YES;
        [mapImg.layer setCornerRadius:8];
        mapImg.backgroundColor = WhiteColor;
        [bottomView addSubview:mapImg];
        [mapImg setImage:[UIImage imageNamed:@"dingwei-3"] forState:UIControlStateNormal];
        
        UILabel *nickName = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(mapImg.frame)+8, 26, bottomView.width-CGRectGetMaxX(mapImg.frame)-131, 24)];
        nickName.font = REAL_MEDIUM_FONT(16);
        nickName.textColor = RealBlackColor;
        nickName.text = @"位置信息";
        [bottomView addSubview:nickName];
        
        UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(nickName.x, CGRectGetMaxY(nickName.frame)+2, nickName.width, 20)];
        time.font = DEFAULT_FONT(13);
        time.textColor = GraryLightColor;
        time.text = [NSString stringWithFormat:@"用时 %@",[_info[@"timeRun"] substringWithRange:NSMakeRange(14, [_info[@"timeRun"] length]-15)]];
        [bottomView addSubview:time];
        
        UILabel *date = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-123, 26, 107, 46)];
        date.font = DEFAULT_FONT(13);
        date.textColor = GraryLightColor;
        date.textAlignment = NSTextAlignmentRight;
        date.text = [NSString stringWithFormat:@"%ld月%ld日",(long)[[_info[@"array"] lastObject][@"create_time"] substringWithRange:NSMakeRange(5, 2)].integerValue,(long)[[_info[@"array"] lastObject][@"create_time"] substringWithRange:NSMakeRange(8, 2)].integerValue];
        [bottomView addSubview:date];
    }
    
    _dotView = [[UIView alloc] initWithFrame:CGRectMake(10, SCREEN_HEIGHT, SCREEN_WIDTH-20, 280)];
    _dotView.backgroundColor = RealWhiteColor;
    [_dotView.layer setCornerRadius:16];
    _dotView.layer.masksToBounds = YES;
    [self.view addSubview:_dotView];
    
    UIButton *dotClose = [[UIButton alloc] initWithFrame:CGRectMake(_dotView.width-40, 7, 26, 26)];
    [dotClose setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [_dotView addSubview:dotClose];
    [[dotClose rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self drawOverlayAndAnnotion];
    }];
        
    UILabel *dotTitle = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-40, 40)];
    dotTitle.font = MEDIUM_FONT(15);
    [_dotView addSubview:dotTitle];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@（轨迹点数%lu）",_info[@"title"],(unsigned long)[_info[@"array"] count]]];
    [str addAttribute:NSForegroundColorAttributeName value:PurpleColor range:NSMakeRange([_info[@"title"] length], str.length-[_info[@"title"] length])];
    [str addAttributes:@{NSFontAttributeName:MEDIUM_FONT(10)} range:NSMakeRange([_info[@"title"] length], str.length-[_info[@"title"] length])];
    dotTitle.attributedText = str;
    
    [_dotView addSubview:self.tableView];
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.mapView removeFromSuperview];
    self.mapView = nil;
    self.mapView.delegate = nil;
}

- (void)drawOverlayAndAnnotion
{
    [UIView animateWithDuration:0.3 animations:^{
        self.dotView.y = SCREEN_HEIGHT;
    }];
    
    [self.mapView removeAnnotations:self.annotationArray];
    [self.mapView removeOverlays:self.overlayArray];
    self.annotationArray = [NSMutableArray array];
    self.overlayArray = [NSMutableArray array];
    
    if ([_info[@"title"] containsString:@"行程"] || [_info[@"title"] containsString:@"驾车"]) {
        CLLocationCoordinate2D satrtCoord = CLLocationCoordinate2DMake([[_info[@"array"] firstObject][@"latitude"] doubleValue],[[_info[@"array"] firstObject][@"longtitude"] doubleValue]);
        MKPointAnnotation *startAnnotation = [[MKPointAnnotation alloc] init];
        startAnnotation.coordinate = satrtCoord;
        startAnnotation.title    = @"start";
        startAnnotation.subtitle = @"start";
        [self.mapView addAnnotation:startAnnotation];
        [self.annotationArray addObject:startAnnotation];
        
        CLLocationCoordinate2D endCoord = CLLocationCoordinate2DMake([[_info[@"array"] lastObject][@"latitude"] doubleValue],[[_info[@"array"] lastObject][@"longtitude"] doubleValue]);
        MKPointAnnotation *endAnnotation = [[MKPointAnnotation alloc] init];
        endAnnotation.coordinate = endCoord;
        endAnnotation.title    = @"end";
        endAnnotation.subtitle = @"end";
        [self.mapView addAnnotation:endAnnotation];
        [self.annotationArray addObject:endAnnotation];
        
        CLLocationCoordinate2D *runningCoords = (CLLocationCoordinate2D *)malloc([_info[@"array"] count] * sizeof(CLLocationCoordinate2D));
        for (int i = 0; i < [_info[@"array"] count]; i++)
        {
            @autoreleasepool
            {
                NSDictionary *data = _info[@"array"][i];
                runningCoords[i].latitude = [data[@"latitude"] doubleValue];
                runningCoords[i].longitude = [data[@"longtitude"] doubleValue];
            }
        }
        
        MKPolyline *polyline = [MKPolyline polylineWithCoordinates:runningCoords count:[_info[@"array"] count]];
        [self.mapView addOverlay:polyline];
        [self.overlayArray addObject:polyline];
        const CGFloat screenEdgeInset = 20;
        UIEdgeInsets inset = UIEdgeInsetsMake(NAVHEIGHT, screenEdgeInset, 320+STATUSHEIGHT, screenEdgeInset);
        [self.mapView setVisibleMapRect:polyline.boundingMapRect edgePadding:inset animated:NO];
    }else{
        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([[_info[@"array"] firstObject][@"latitude"] doubleValue],[[_info[@"array"] firstObject][@"longtitude"] doubleValue]);
        _annotation = [[MKPointAnnotation alloc] init];
        _annotation.coordinate = coord;
        _annotation.title = @"location";
        [self.mapView addAnnotation:_annotation];
        [self.mapView setCenterCoordinate:coord animated:NO];
        [self.annotationArray addObject:_annotation];
    }
}

- (void)drawTrackDotOverlayAndAnnotion
{
    [UIView animateWithDuration:0.3 animations:^{
        self.dotView.y = SCREEN_HEIGHT-STATUSHEIGHT-312;
    }];
    [self.mapView removeAnnotations:self.annotationArray];
    [self.mapView removeOverlays:self.overlayArray];
    self.annotationArray = [NSMutableArray array];
    self.overlayArray = [NSMutableArray array];
    
    if ([_info[@"title"] containsString:@"行程"] || [_info[@"title"] containsString:@"驾车"]) {
        for (int i = 0; i < [_info[@"array"] count]; i++) {
            NSDictionary *data = _info[@"array"][i];
            CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([data[@"latitude"] doubleValue],[data[@"longtitude"] doubleValue]);
            MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
            annotation.coordinate = coord;
            annotation.title    = @"dot_location";
            annotation.subtitle = data[@"create_time"];
            [self.mapView addAnnotation:annotation];
            [self.annotationArray addObject:annotation];
        }
        
        
        CLLocationCoordinate2D *runningCoords = (CLLocationCoordinate2D *)malloc([_info[@"array"] count] * sizeof(CLLocationCoordinate2D));
        for (int i = 0; i < [_info[@"array"] count]; i++)
        {
            @autoreleasepool
            {
                NSDictionary *data = _info[@"array"][i];
                runningCoords[i].latitude = [data[@"latitude"] doubleValue];
                runningCoords[i].longitude = [data[@"longtitude"] doubleValue];
            }
        }
        
        MKPolyline *polyline = [MKPolyline polylineWithCoordinates:runningCoords count:[_info[@"array"] count]];
        [self.mapView addOverlay:polyline];
        [self.overlayArray addObject:polyline];
        const CGFloat screenEdgeInset = 20;
        UIEdgeInsets inset = UIEdgeInsetsMake(20, screenEdgeInset, 260, screenEdgeInset);
        [self.mapView setVisibleMapRect:polyline.boundingMapRect edgePadding:inset animated:NO];
    }else{
        for (int i = 0; i < [_info[@"array"] count]; i++) {
            NSDictionary *data = _info[@"array"][i];
            CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([data[@"latitude"] doubleValue],[data[@"longtitude"] doubleValue]);
            MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
            annotation.coordinate = coord;
            annotation.title    = @"dot_location";
            annotation.subtitle = data[@"create_time"];
            [self.mapView addAnnotation:annotation];
            [self.annotationArray addObject:annotation];
            if (i==0) {
                [self.mapView setCenterCoordinate:coord animated:NO];
            }
        }
    }
    
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation.title isEqualToString:@"location"]) {
        static NSString *customReuseIndetifier = @"MemberTrackDetailAnnotationView";
        MemberTrackDetailAnnotationView *annotationView = (MemberTrackDetailAnnotationView* )[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[MemberTrackDetailAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }

        return annotationView;
    }else if ([annotation.title isEqualToString:@"end"]){
        static NSString *customReuseIndetifier = @"RouteAnnotationView";
        RouteAnnotationView *annotationView = (RouteAnnotationView* )[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[RouteAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.calloutOffset = CGPointMake(0, -5);
            annotationView.locationImg.image = [UIImage imageNamed:@"dingwei-4"];
        }
        return annotationView;
    }else if ([annotation.title isEqualToString:@"dot_location"]){
        static NSString *customReuseIndetifier = @"TrackDotAnnotationView";
        TrackDotAnnotationView *annotationView = (TrackDotAnnotationView* )[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[TrackDotAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        annotationView.head.backgroundColor = annotationView.selected?PurpleColor:GraryTooHeavyColor;
        return annotationView;
    }else{
        static NSString *customReuseIndetifier = @"TrackEventAnnotationView";
        TrackEventAnnotationView *annotationView = (TrackEventAnnotationView* )[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[TrackEventAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        if ([annotation.title isEqualToString:@"unlock"]) {
            annotationView.subLayer.backgroundColor = RealWhiteColor.CGColor;
            annotationView.mapImg.backgroundColor = YellowColor;
        }else if ([annotation.title isEqualToString:@"bark"]){
            annotationView.subLayer.backgroundColor = RealWhiteColor.CGColor;
            annotationView.mapImg.backgroundColor = RedColor;
        }else if ([annotation.title isEqualToString:@"start"]){
            annotationView.subLayer.backgroundColor = RealBlackColor.CGColor;
            annotationView.mapImg.backgroundColor = RealWhiteColor;
        }
        
        return annotationView;
    }
    
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    if ([view isKindOfClass:[TrackDotAnnotationView class]]) {
        for (MKPointAnnotation *annotion in self.annotationArray) {
            ((TrackDotAnnotationView *)[self.mapView viewForAnnotation:annotion]).selected = NO;
            ((TrackDotAnnotationView *)[self.mapView viewForAnnotation:annotion]).head.backgroundColor = GraryTooHeavyColor;
        }
        ((TrackDotAnnotationView *)view).selected = YES;
        ((TrackDotAnnotationView *)view).head.backgroundColor = PurpleColor;
        [self.mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
    }
    for (int i = 0; i<[self.info[@"array"] count]; i++) {
        NSDictionary *dic = self.info[@"array"][i];
        if ([dic[@"create_time"] isEqualToString:view.annotation.subtitle]) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [self.tableView selectRowAtIndexPath:indexPath animated:YES
                                  scrollPosition:UITableViewScrollPositionMiddle];
            break;
        }
    }
}

#pragma mark - mapview delegate
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
//    GradientPathRenderer *polylineRenderer = [[GradientPathRenderer alloc] initWithLine:(MKPolyline *)overlay Colors:@[
//        [UIColor colorWithRed:114/255.0 green:93/255.0 blue:234/255.0 alpha:1/1.0],
//        [UIColor colorWithRed:114/255.0 green:127/255.0 blue:250/255.0 alpha:1/1.0],
//        [UIColor colorWithRed:114/255.0 green:127/255.0 blue:250/255.0 alpha:1/1.0],
//        [UIColor colorWithRed:84/255.0 green:111/255.0 blue:250/255.0 alpha:1/1.0],
//        [UIColor colorWithRed:114/255.0 green:93/255.0 blue:234/255.0 alpha:1/1.0],
//        [UIColor colorWithRed:114/255.0 green:127/255.0 blue:250/255.0 alpha:1/1.0],
//        [UIColor colorWithRed:142/255.0 green:123/255.0 blue:249/255.0 alpha:1/1.0]
//    ]];
    MKPolylineRenderer *polylineRenderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    polylineRenderer.lineWidth = 5.f;
    polylineRenderer.strokeColor =  [UIColor colorWithRed:88/255.0 green:101/255.0 blue:242/255.0 alpha:1/1.0];
    return polylineRenderer;
}

- (void)mapViewDidChangeVisibleRegion:(MKMapView *)mapView
{
    BOOL showTraffic = [[[NSUserDefaults standardUserDefaults] objectForKey:ShowTraffic] boolValue];
    NSInteger roadNet = [[[NSUserDefaults standardUserDefaults] objectForKey:RoadNet] boolValue];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:MapType] integerValue]==2) {
        if (self.mapView.zoomLevel>16.0) {
            self.mapView.mapType = (showTraffic==0)?(roadNet==0?MKMapTypeSatellite:MKMapTypeHybrid):MKMapTypeHybridFlyover;
        }else{
            self.mapView.mapType = MKMapTypeStandard;
        }
    }
    CLLocationCoordinate2D loc = [self.mapView convertPoint:CGPointMake(0, 0) toCoordinateFromView:self.mapView];
    
    double distance = [self distanceBetweenOrderByLatitudeA:loc.latitude latitudeB:self.mapView.centerCoordinate.latitude longitudeA:loc.longitude longitudeB:self.mapView.centerCoordinate.longitude];
    
    MemberTrackDetailAnnotationView *annotationView = (MemberTrackDetailAnnotationView *)[self.mapView viewForAnnotation:self.annotation];
    double scale = 1.52/distance;
    [annotationView setBounds:CGRectMake(0, 0, 200*scale, 200*scale)];
    [annotationView.layer setCornerRadius:100*scale];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.info[@"array"] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"TrackDotTableViewCell";
    TrackDotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[TrackDotTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    [cell loadWithInfo:self.info[@"array"][indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    for (MKPointAnnotation *annotion in self.annotationArray) {
        if ([annotion.subtitle isEqualToString:self.info[@"array"][indexPath.row][@"create_time"]]) {
            ((TrackDotAnnotationView *)[self.mapView viewForAnnotation:annotion]).selected = YES;
            ((TrackDotAnnotationView *)[self.mapView viewForAnnotation:annotion]).head.backgroundColor = PurpleColor;
            [self.mapView setCenterCoordinate:annotion.coordinate animated:YES];
        }else{
            ((TrackDotAnnotationView *)[self.mapView viewForAnnotation:annotion]).selected = NO;
            ((TrackDotAnnotationView *)[self.mapView viewForAnnotation:annotion]).head.backgroundColor = GraryTooHeavyColor;
        }
    }
}

- (double)distanceBetweenOrderByLatitudeA:(double)latitude1 latitudeB:(double)latitude2 longitudeA:(double)longitude1 longitudeB:(double)longitude2
{
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:latitude1 longitude:longitude1];
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:latitude2 longitude:longitude2];
    double  distance = [curLocation distanceFromLocation:otherLocation]/1000;
    return  distance;
}

- (NSMutableArray *)annotationArray
{
    if (!_annotationArray) {
        _annotationArray = [[NSMutableArray alloc] init];
    }
    return _annotationArray;
}

- (NSMutableArray *)overlayArray
{
    if (!_overlayArray) {
        _overlayArray = [[NSMutableArray alloc] init];
    }
    return _overlayArray;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, self.dotView.width, self.dotView.height-40) style:UITableViewStylePlain];
        _tableView.estimatedRowHeight = 0;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableView.fillerRowHeight = 0;
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = RealWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

@end
